//
//  wxpayTool.m
//  LiverClient
//
//  Created by dongshangtong on 16/6/8.
//  Copyright © 2016年 朱亚杰. All rights reserved.
//

#import "wxpayTool.h"

#import <CommonCrypto/CommonDigest.h>


@implementation wxpayTool


//md5 encode
+ (NSString *)stringMd5WithString:(NSString *)str {
    const char *cStr = [str UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    CC_MD5( cStr, (unsigned int)strlen(cStr), digest );
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}


/**
 *  按照官方要求生成签名
 *
 *  @param dict https://pay.weixin.qq.com/wiki/doc/api/app.php?chapter=4_3
 *
 *  @return 签名
 */
+ (NSString *)createMd5Sign:(NSMutableDictionary *)dict {
    
    
    NSMutableString *contentString = [NSMutableString string];
    NSArray *keys = [dict allKeys];
    // 按字母顺序排序, 官方要求参数必须按照参数名ASCII码从小到大排序（字典序）
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (   ![[dict objectForKey:categoryId] isEqualToString:@""]
            && ![categoryId isEqualToString:@"sign"]
            && ![categoryId isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [dict objectForKey:categoryId]];
        }
        
    }
    //添加key字段
    [contentString appendFormat:@"key=%@", XPartnerID];
    
    //返回得到MD5 sign签名
    return [self stringMd5WithString:contentString];
}



/**
 *  获取确认支付所需参数
 *
 *  @param prepayID 获取到的预支付标记
 */
+ (NSMutableDictionary *)createWXRequestParameterWith:(NSString *)prepayID {
    //获取到prepayid后进行第二次签名
    NSString    *package, *time_stamp, *nonce_str;
    
    //设置支付参数
    time_t now;
    time(&now);
    time_stamp  = [NSString stringWithFormat:@"%ld", now];
    nonce_str	= [self stringMd5WithString:time_stamp];
    
    // 重新按提交格式组包，微信客户端暂只支持package=Sign=WXPay格式，须考虑升级后支持携带package具体参数的情况
    // package       = [NSString stringWithFormat:@"Sign=%@",package];
    package         = @"Sign=WXPay";
    
    // 第二次签名参数列表
    NSMutableDictionary *signParas = [NSMutableDictionary dictionary];
    [signParas setObject: AppID        forKey:@"appid"];
    [signParas setObject: nonce_str    forKey:@"noncestr"];
    [signParas setObject: package      forKey:@"package"];
    [signParas setObject: MchID        forKey:@"partnerid"];
    [signParas setObject: time_stamp   forKey:@"timestamp"];
    [signParas setObject: prepayID     forKey:@"prepayid"];
    //[signParams setObject: @"MD5"       forKey:@"signType"];
    
    // 生成签名
    NSString *sign  = [self createMd5Sign:signParas];
    
    // 添加签名
    [signParas setObject: sign         forKey:@"sign"];
    
    return signParas;
}



//32为的随机字符串
+(NSString *)stringnonceStr
{
    
    
    NSArray *arr =@[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
    
    NSMutableString *nonceStr = [[NSMutableString alloc]init];
    
    for (int i=0; i<32; i++) {
        
        
        [nonceStr appendString:arr[(arc4random()%36 )]];
    }
    
    return nonceStr;
}


@end
